<template>
  <div style="padding:10px 20px">
    <!-- 顶级筛选 -->
    <div class="top-filter">
      <div class="tab-bar">
        <span class="tab" :class="{ 'active': currentTab === 'all' }" @click="changeTab('all')">全部</span>
        <span
          class="tab"
          :class="{ 'active': currentTab === 'created' }"
          @click="changeTab('created')"
        >我创建的</span>
      </div>

      <div class="search-container">
        <div class="search-input-wrapper">
          <input v-model="searchQuery" placeholder="搜索题目" class="search-input" />
          <img
            src="@/assets/picture/find.png"
            alt="搜索"
            class="search-icon"
            @click="searchQuestions"
          />
        </div>
        <button  v-if="!isPopupMode" @click="openNewQuestionMenu" class="action-button">新建题目</button>
        <div v-if="newQuestionMenuVisible" class="new-question-menu">
          <span @click="showAddDialog('only_sel')">单选题</span>
          <span @click="showAddDialog('many_sel')">多选题</span>
          <span @click="showAddDialog('yesorno')">判断题</span>
          <span @click="showAddDialog('qna')">简答题</span>
        </div>
      </div>
    </div>

    <!-- 二级筛选 -->
    <div class="secondary-filters">
      <!-- 方向筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">专业:</p>
        <span
          @click="toggleFilterDirection('all')"
          :class="{ 'active-filter': selectedFilterDirection === 'all' }"
        >全部</span>
        <span
          v-for="direction in directions"
          :key="direction.direction_id"
          @click="toggleFilterDirection(direction.direction_id)"
          :class="{ 'active-filter': selectedFilterDirection === direction.direction_id }"
        >
          {{ direction.direction_title }}
        </span>
      </div>
      <div class="filter-group" v-if="selectedFilterDirection !== 'all'">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">方向:</p>
        <span
          @click="toggleFilterPoint('all')"
          :class="{ 'active-filter': selectedFilterPoint === 'all' }"
        >全部</span>
        <span 
          v-for="point in directions.find(dir => dir.direction_id === selectedFilterDirection)?.points || []"
          :key="point.point_id"
          @click="toggleFilterPoint(point.point_id)"
          :class="{ 'active-filter': selectedFilterPoint === point.point_id }"
        >
          {{ point.point_content }}
        </span>
      </div>

      <!-- 题型筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">题型:</p>
        <span
          @click="toggleFilterQuestionType('all')"
          :class="{ 'active-filter': selectedQuestionType === 'all' }"
        >全部</span>
        <span
          @click="toggleFilterQuestionType('only_sel')"
          :class="{ 'active-filter': selectedQuestionType === 'only_sel' }"
        >单选题</span>
        <span
          @click="toggleFilterQuestionType('many_sel')"
          :class="{ 'active-filter': selectedQuestionType === 'many_sel' }"
        >多选题</span>
        <span
          @click="toggleFilterQuestionType('yesorno')"
          :class="{ 'active-filter': selectedQuestionType === 'yesorno' }"
        >判断题</span>
        <span
          @click="toggleFilterQuestionType('qna')"
          :class="{ 'active-filter': selectedQuestionType === 'qna' }"
        >简答题</span>
      </div>

      <!-- 难度筛选 -->
      <div class="filter-group">
        <p class="filter-label" style="color: #333333;padding: 0px 12px;">难度:</p>
        <span
          @click="toggleFilterDifficulty('all')"
          :class="{ 'active-filter': selectedDifficulty === 'all' }"
        >全部</span>
        <span
          @click="toggleFilterDifficulty('0')"
          :class="{ 'active-filter': selectedDifficulty === '0' }"
        >简单</span>
        <span
          @click="toggleFilterDifficulty('1')"
          :class="{ 'active-filter': selectedDifficulty === '1' }"
        >中等</span>
        <span
          @click="toggleFilterDifficulty('2')"
          :class="{ 'active-filter': selectedDifficulty === '2' }"
        >困难</span>
      </div>
    </div>

    <div v-if="currentTab === 'created'" style="margin-bottom: 10px;">
      <button
        @click="batchDeleteSelectedQuestions"
        :disabled="selectedQuestions.length === 0"
        class="action-button"
        style="background-color: #f44336;"
      >批量删除</button>
    </div>

    <!-- 题目表格 -->
    <table class="question-table">
      <colgroup>
        <col v-if="currentTab === 'created'" style="width: 6%;" />
        <col style="width: 62%;" />
        <col style="width: 7%;" />
        <col style="width: 15%;" />
        <col style="width: 10%;" />
      </colgroup>
      <thead>
        <tr>
          <th v-if="currentTab === 'created'">
            <input type="checkbox" v-model="allSelected" @change="toggleSelectAll" />
          </th>
          <th>题目描述</th>
          <th>难度</th>
          <th>方向</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="question in paginatedData" :key="question.qs_id" class="table-row">
          <!-- 现有的题目显示代码 -->
          <td v-if="currentTab === 'created'">
            <input type="checkbox" :value="question.qs_id" v-model="selectedQuestions" />
          </td>
          <td>
            <details class="question-details">
              <summary style="cursor: pointer;">
                <span class="question-type" style="color:gray">[{{ getQuestionType(question.qs_type) }}]</span>
                <span>{{ question.qs_title.replace(/<[^>]*>?/gm, '') }}</span>
              </summary>
              <div class="question-options" style="margin-left:60px">
                <!-- 仅选择题类型显示选项 -->
                <div v-if="question.qs_type === 'only_sel' || question.qs_type === 'many_sel'">
                  <div
                    v-for="(option, index) in question.options"
                    :key="option.option_id"
                    style="padding-bottom: 5px;"
                  >
                    {{ String.fromCharCode(65 + index) }}. {{ option.option_content }}
                    <span
                      v-if="option.is_right"
                      style="font-weight:bold;color:#4CAF50"
                    >√</span>
                  </div>
                </div>
                <!-- 判断题类型显示选项 -->
                <div v-if="question.qs_type === 'yesorno'" style="padding-bottom: 5px;">
                  <div
                    v-for="(option, index) in question.options"
                    :key="option.option_id"
                    style="padding-bottom: 5px;"
                  >
                    {{ String.fromCharCode(65 + index) }}. {{ option.option_content }}
                    <span
                      v-if="option.is_right"
                      style="font-weight:bold;color:#4CAF50"
                    >√</span>
                  </div>
                </div>

                <!-- 简答题显示答案 -->
                <div v-if="question.qs_type === 'qna'" style="padding-top: 10px;">
                  <strong>答案:</strong>
                  <span v-html="question.right_ans"></span>
                </div>
              </div>
            </details>
          </td>
          <td>{{ getDifficultyLabel(question.difficulty) }}</td>
          <td>{{ question.point_content }}</td>
          <td class="action-cell">
  <div v-if="currentTab === 'created' && !isPopupMode" class="action-buttons">
    <button @click="editQuestion(question)" class="edit-button">编辑</button>
    <button @click="deleteQuestionHandler(question)" class="delete-button">删除</button>
  </div>
  <button v-if="isPopupMode" 
          @click="selectQuestionForPopup(question.qs_id)" 
          :class="['select-button', { 'selected': question.isSelected }]"
  >
    {{ question.isSelected ? '从试卷移除' : '添加到试卷' }}
  </button>
</td>

        </tr>
        <!-- 当无结果时显示提示 -->
        <tr v-if="paginatedData.length === 0">
          <td :colspan="currentTab === 'created' ? '5' : '4'" class="no-results">没有找到匹配的题目。</td>
        </tr>
      </tbody>
    </table>

    <!-- 分页 -->
    <Pagination
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-change="handlePageChange"
    />

    <!-- 新建题目的弹窗 -->
    <div v-if="AdddialogVisible" class="modal">
      <div class="modal-content">
        <h3>添加题目</h3>
        <div
          class="form-group"
          style="display: flex;justify-content: space-between;align-items: center;"
        >
          <div>
           <label for="direction">题目方向:</label>
          <select v-model="Addform.direction" id="direction" style="height: 30px;border: 1px solid #8080805c;color: gray;margin-left: 5px;width:200px">
            <option value="">请选择题目方向</option>
            <option
              v-for="direction in directions"
              :key="direction.direction_id"
              style="display:none"
            >
              {{ direction.direction_title }}
            </option>
            <template v-for="direction in directions" :key="direction.direction_id">
              <option
                v-for="point in (direction.points || [])"
                :key="point.point_id"
                :value="point.point_id"
              >
                &nbsp;&nbsp;{{ point.point_content }}
              </option>
            </template>
          </select>
          </div>
          <div>
            <!-- 难度选择 -->
            <label for="difficulty" style="margin-right:10px">题目难度:</label>
            <select
              v-model="Addform.difficulty"
              id="difficulty"
              required
              style="height: 30px;border: 1px solid #8080805c;color: gray;margin-left: 5px;width:200px"
            >
              <option value>选择难度</option>
              <option value="0">简单</option>
              <option value="1">中等</option>
              <option value="2">困难</option>
            </select>
          </div>
        </div>

        <!-- 题目描述 -->
        <label>题目描述:</label>
        <QuillEditor style="margin-bottom:10px" v-model="Addform.title" />

        <!-- 根据题型动态显示选项 -->
        <div v-if="Addform.qs_type === 'only_sel' || Addform.qs_type === 'many_sel'">
          <label>{{ Addform.qs_type === 'only_sel' ? '单选题选项:' : '多选题选项:' }}</label>
          <div
            v-for="(option, index) in options"
            :key="option.option_id || index"
            class="option-group"
            style="display: flex; align-items: center; margin-bottom: 5px;"
          >
            <!-- 单选题 -->
            <input
              type="radio"
              v-if="Addform.qs_type === 'only_sel'"
              :name="'singleOption'"
              v-model="correctOption"
              :value="index"
              @change="handleOptionChange(index)"
            />
            <!-- 多选题 -->
            <input
              type="checkbox"
              v-if="Addform.qs_type === 'many_sel'"
              :name="'multiOption'"
              v-model="option.is_right"
              :value="true"
            />
            <input
              type="text"
              v-model="option.content"
              placeholder="选项内容"
              class="input-field option-input"
              style
            />
            <!-- 仅在最后一个选项显示 + 和 - 按钮 -->
            <div v-if="index === options.length - 1" class="option-buttons">
              <button
                type="button"
                @click="addOption"
                :disabled="options.length === 4"
                class="option-button"
                title="添加选项"
                style="margin-right:10px"
              >
                <img src="@/assets/picture/add.png" alt="添加" />
              </button>
              <button
                type="button"
                @click="removeOption(index)"
                class="option-button"
                :disabled="options.length === 1"
                title="删除选项"
              >
                <img src="@/assets/picture/delete.png" alt="删除" />
              </button>
            </div>
          </div>
        </div>

        <!-- 判断题 -->
        <div v-if="Addform.qs_type === 'yesorno'">
          <label>判断题选项:</label>
          <div class="option-group">
            <input type="radio" v-model="isRight" :value="true" /> 正确
            <input type="radio" v-model="isRight" :value="false" /> 错误
          </div>
        </div>

        <!-- 简答题 -->
        <div v-if="Addform.qs_type === 'qna'">
          <label>简答题答案:</label>
          <QuillEditor v-model="Addform.answer" />
        </div>

        <div class="modal-buttons">
          <button @click="AdddialogVisible = false" class="cancel-button">取消</button>
          <button @click="AddsaveQuestion" class="confirm-button">保存</button>
        </div>
      </div>
    </div>

    <!-- 编辑题目的弹窗 -->
    <div v-if="EditdialogVisible" class="modal">
      <div class="modal-content">
        <h3>编辑题目</h3>
        <div
          class="form-group"
          style="display: flex;justify-content: space-between;align-items: center;"
        >
          <div>
            <label for="direction">题目方向:</label>
              <select v-model="Editform.point_id" id="direction" style="height: 30px;border: 1px solid #8080805c;color: gray;margin-left: 5px;width:200px">
                <option value="">请选择题目方向</option>
                <option
                  v-for="direction in directions"
                  :key="direction.direction_id"
                  style="display:none"
                >
                  {{ direction.direction_title }}
                </option>
                <template v-for="direction in directions" :key="direction.direction_id">
                  <option
                    v-for="point in (direction.points || [])"
                    :key="point.point_id"
                    :value="point.point_id"
                  >
                    &nbsp;&nbsp;{{ point.point_content }}
                  </option>
                </template>
              </select>
          </div>
          <div>
            <!-- 难度选择 -->
            <label for="difficulty" style="margin-right:10px">题目难度:</label>
            <select v-model="Editform.difficulty" id="difficulty" required style="height: 30px;border: 1px solid #8080805c;color: gray;margin-left: 5px;width:200px">
              <option value>选择难度</option>
              <option value="0">简单</option>
              <option value="1">中等</option>
              <option value="2">困难</option>
            </select>
          </div>
        </div>

        <!-- 题目描述 -->
        <label>题目描述:</label>
        <QuillEditor style="margin-bottom:10px" v-model="Editform.qs_title" />

        <!-- 根据题型动态显示选项 -->
        <div v-if="Editform.qs_type === 'only_sel' || Editform.qs_type === 'many_sel'">
          <label>{{ Editform.qs_type === 'only_sel' ? '单选题选项:' : '多选题选项:' }}</label>
          <div
            v-for="(option, index) in Editoptions"
            :key="index"
            class="option-group"
            style="display: flex; align-items: center; margin-bottom: 5px;"
          >
            <!-- 单选题 -->
            <input
              type="radio"
              v-if="Editform.qs_type === 'only_sel'"
              :name="'singleOption'"
              v-model="option.is_right"
              :value="true"
              @change="updateOnlySelCorrectOption(index)"
            />
            <!-- 多选题 -->
            <input
              type="checkbox"
              v-if="Editform.qs_type === 'many_sel'"
              :name="'multiOption'"
              v-model="option.is_right"
              :value="true"
            />
            <input
              type="text"
              v-model="option.content"
              placeholder="选项内容"
              class="input-field option-input"
              style
            />
            <!-- 仅在最后一个选项显示 + 和 - 按钮 -->
            <div v-if="index === Editoptions.length - 1" class="option-buttons">
              <button
                type="button"
                @click="addOption1(index+1)"
                :disabled="Editoptions.length === 4"
                class="option-button"
                title="添加选项"
                style="margin-right:10px"
              >
                <img src="@/assets/picture/add.png" alt="添加" />
              </button>
              <button
                type="button"
                @click="removeOption1(index,option.option_id)"
                class="option-button"
                :disabled="Editoptions.length === 1"
                title="删除选项"
              >
                <img src="@/assets/picture/delete.png" alt="删除" />
              </button>
            </div>
          </div>
        </div>

        <!-- 判断题 -->
        <div v-if="Editform.qs_type === 'yesorno'">
          <label>判断题选项:</label>
          <div class="option-group">
            <input type="radio" v-model="isRight" :value="true" /> 正确
            <input type="radio" v-model="isRight" :value="false" /> 错误
          </div>
        </div>

        <!-- 简答题 -->
        <div v-if="Editform.qs_type === 'qna'">
          <label>简答题答案:</label>
          <QuillEditor v-model="Editform.right_ans" />
        </div>

        <div class="modal-buttons">
          <button @click="EditdialogVisible = false" class="cancel-button">取消</button>
          <button @click="EditsaveQuestion" class="confirm-button">保存</button>
        </div>
      </div>
    </div>
     <!-- 确认选择按钮 -->
<div v-if="isPopupMode" style="margin-top: 20px; text-align: right;">
<div v-if="selectedQuestionsPopup && selectedQuestionsPopup.length > 0">
  <span>已选择题目 ID: {{ selectedQuestionsPopup.join(', ') }}</span>
</div>

  <button style="margin-right:20px" @click="confirmSelection" class="confirm-button">确认选择</button>
  <button @click="closeDialog" class="cancel-button">取消</button>
</div>

  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage,ElMessageBox  } from 'element-plus';
import {
  getQuestionDirections,
  fetchQuestions,
  saveQuestion,
  deleteQuestion,
  getSingleQuestion,
  updateQuestion,
  batchDeleteQuestions,
  saveShortAnswerQuestionApi
} from "@/services/api";

import Pagination from "@/components/PagiNation.vue";
import QuillEditor from "@/components/QuillEditor.vue";


export default {
  name: "T_QuestionBankPage",
  components: {
    Pagination,
    QuillEditor
  },
  props: {
  isPopupMode: {
    type: Boolean,
    default: false
  }
},
  setup(props, { emit }) {
    const currentTab = ref("all");
    const questions = ref([]);
    const Addform = ref({
      title: "",
      qs_type: "",
      direction: "",
      answer: "",
      difficulty: "",
      qs_id: null // 新增 qs_id 用于编辑
    });
    const Editform = ref({
      title: "",
      qs_type: "",
      direction: "",
      answer: "",
      difficulty: "",
      qs_id: "",
      options:[],
      update_options:[],
      delete_options: [] // 确保这里是一个空数组

    });
    // const filteredTitle = computed(() => {
    //   const tempDiv = document.createElement('div');
    //   tempDiv.innerHTML = props.question.qs_title;
    //   const paragraphs = tempDiv.getElementsByTagName('p');
    //   return paragraphs.length > 0 ? paragraphs[0].innerHTML : ''; // 只返回第一个 <p> 的内容
    // });
    const selectedQuestionsPopup = ref([]); // 用于弹窗模式下保存选中的题目

const selectQuestionForPopup = (qs_id) => {
  // 找到当前被点击的题目
  const question = questions.value.find(q => q.qs_id === qs_id);

  if (question) {
    // 切换题目的选中状态
    question.isSelected = !question.isSelected;

    if (question.isSelected) {
      // 如果是选中状态，将题目 ID 添加到 selectedQuestionsPopup 数组
      selectedQuestionsPopup.value.push(qs_id);
      console.log(question);
    } else {
      // 如果取消选中，从 selectedQuestionsPopup 数组中移除
      selectedQuestionsPopup.value = selectedQuestionsPopup.value.filter(
        (id) => id !== qs_id
      );
    }
  }
};

    const options = ref([{ content: "", is_right: false }]); // 默认有一个输入框
    const Editoptions=ref([{option_id:"",content:'',is_right:false}]);
    const AdddialogVisible = ref(false);
    const EditdialogVisible = ref(false);
    const currentPage = ref(1);
    const pageSize = 10;
    const searchQuery = ref("");
    const selectedFilterDirection = ref("all");
    const selectedQuestionType = ref("all");
    const selectedDifficulty = ref("all");
    const newQuestionMenuVisible = ref(false);
    const directions = ref([]);
    const selectedFilterPoint = ref("all"); // 选中的题目方向（point）
    const tech_id = ref(localStorage.getItem("id") || "");
    const correctOption=ref('');
    //新增选项
    const Insertoptions=[];
    // 删除选项
    const deleteOptionList=[];
    //获取Editoptions初始回显长度
    let EditOptionsLength=0;
    const handleOptionChange = index => {
      correctOption.value = index; // 更新选中的索引
    };

    const updateOnlySelCorrectOption = (selectedIndex) => {
  isRight.value = selectedIndex === 0; // 这里更新 isRight 的值
  Editoptions.value.forEach((option, index) => {
    option.is_right = index === selectedIndex;
  });
};

    const confirmSelection = () => {
      // 发出选择的题目 ID 列表
      emit("selectQuestions", selectedQuestionsPopup.value);
      selectedQuestionsPopup.value = []; // 清空选中列表，确保下一次使用时不会遗留
    };

    const closeDialog = () => {
      emit("close");
    };
    const selectedQuestions = ref([]);
    const allSelected = computed({
      get: () => {
        if (paginatedData.value.length === 0) return false;
        return paginatedData.value.every(q =>
          selectedQuestions.value.includes(q.qs_id)
        );
      },
      set: value => {
        if (value) {
          selectedQuestions.value = paginatedData.value.map(q => q.qs_id);
        } else {
          selectedQuestions.value = [];
        }
      }
    });

    const toggleSelectAll = () => {
      if (allSelected.value) {
        selectedQuestions.value = paginatedData.value.map(q => q.qs_id);
      } else {
        selectedQuestions.value = [];
      }
    };

    watch(
      [
        currentTab,
        searchQuery,
        selectedFilterDirection,
        selectedQuestionType,
        selectedDifficulty
      ],
      () => {
        selectedQuestions.value = [];
      }
    );
    //    添加功能
    const addOption = () => {
      console.log("Add option clicked");
      if (options.value.length < 4) {
        options.value.push({ content: "", is_right: false });
      }
    };

    const removeOption = index => {
      console.log("Remove option clicked", index);
      if (options.value.length > 1) {
        options.value.splice(index, 1);
        // console.log(option.option_id);
      }
    };
    //編輯功能
    const addOption1 = (index) => {
      console.log("Add option clicked");
      console.log(Editoptions.value);
      if (Editoptions.value.length < 4) {
        Editoptions.value.push({ content: "", is_right: false,is_insert:true });
        console.log("index:",index);
        console.log(Editoptions.value[index]);
      }
    };

const removeOption1 = (index, id) => {
  console.log("Remove option clicked", index);
  
  // 确保使用 Editform.value.options
      if (Editoptions.value.length > 1) {
        Editoptions.value.splice(index, 1);
      }

  // 确保正确访问 delete_options
  deleteOptionList.push({
      option_id: id 
  });

};

    // 判断题选项的状态
    const isRight = ref(true); // 默认选择正确

    // 映射难度字符串到数值
    // const difficultyMap = {
    //   简单: "0",
    //   中等: "1",
    //   困难: "2"
    // };

    // 获取方向列表
   const fetchDirections = async () => {
      try {
        const response = await getQuestionDirections();
        if (response.data.status === 1) {
          directions.value = response.data.data; // 直接存储筛选方向及其题目方向
          const q = response.data.data;
           Editform.value = {
            ...Editform.value,
            point_id: q.point_id,  // 确保设置方向ID
            // ...其他字段
          };
        } else {
          ElMessage.error("获取方向列表失败");
        }
      } catch (error) {
        console.error("Error fetching directions:", error);
        ElMessage.error("网络错误，无法获取方向列表");
      }
    };

    // 获取题目列表
    const fetchQuestionsData = async () => {
      try {
        const qsTypeMap = {
          only_sel: 1,
          many_sel: 2,
          yesorno: 3,
          qna: 4
        };
        const params = {
          tech_id: currentTab.value === "created" ? tech_id.value : null,
          qs_type:
            selectedQuestionType.value !== "all"
              ? qsTypeMap[selectedQuestionType.value]
              : null,
          point_id: selectedFilterPoint.value !== "all" ? selectedFilterPoint.value : null,
          difficulty:
            selectedDifficulty.value !== "all" ? selectedDifficulty.value : null // 直接使用字符串
        };
        const response = await fetchQuestions(params);
        // question.value=[];
        if (response.data.status === 1) {
 
          questions.value = response.data.data.map(q => ({
            ...q,
              isSelected: false,  // 增加 isSelected 属性来追踪是否被选中
        right_ans: q.right_ans || "" // 确保有 right_ans 字段
          }));
        } else {
          ElMessage.error("这个分类暂时没有试题");
        }
      } catch (error) {
        console.error("Failed to fetch questions:", error);
      }
    };

    // 筛选的计算属性
    const filteredQuestions = computed(() => {
      let filtered = questions.value;

      if (searchQuery.value.trim() !== "") {
        filtered = filtered.filter(q =>
          q.qs_title.includes(searchQuery.value.trim())
        );
      }
      console.log(filtered);

      return filtered;
    });

    const paginatedData = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize;
      return filteredQuestions.value.slice(startIndex, startIndex + pageSize);
    });

    const totalPages = computed(() =>
      Math.ceil(filteredQuestions.value.length / pageSize)
    );

    const changeTab = tab => {
      currentTab.value = tab;
      currentPage.value = 1;
      fetchQuestionsData(); // 切换标签后重新获取数据
    };

    const openNewQuestionMenu = () => {
      newQuestionMenuVisible.value = !newQuestionMenuVisible.value;
    };

    const showAddDialog = type => {
      resetForm();
      Addform.value.qs_type = type; // 设置为传入的类型
      AdddialogVisible.value = true;
      newQuestionMenuVisible.value = false;

      // 根据题型初始化选项
      if (type === "yesorno") {
        options.value = [
          { content: "正确", is_right: true },
          { content: "错误", is_right: false }
        ];
      } else if (type === "qna") {
        options.value = []; // 简答题不需要选项
      } else {
        options.value = [{ content: "", is_right: false }]; // 其他题型初始化一个选项
      }
    }; 

    const editQuestion = async question => {
      try {
        EditdialogVisible.value=true;
        const response = await getSingleQuestion(question.qs_id);
        if (response.data.status === 1) {
        const q = response.data.data;
         Editform.value = {
            qs_title: q.qs_title,
            qs_type: q.qs_type,
            point_id: q.point_id,
             difficulty: q.difficulty, // 确保此处正确赋值
            right_ans: q.right_ans || "",
            qs_id: q.qs_id ,// 用于更新
          };
console.log("Fetched question difficulty:", q.difficulty);

      
          if (q.qs_type === "yesorno") {
            isRight.value = q.options.find(opt => opt.is_right)?.option_content === "正确";
            const correctOptionId = q.options.find(opt => opt.option_content === "正确")?.option_id;
            const wrongOptionId = q.options.find(opt => opt.option_content === "错误")?.option_id;
            Editoptions.value = [
              { option_id: correctOptionId,content: "正确", is_right: isRight.value },
              { option_id: wrongOptionId,content: "错误", is_right: !isRight.value }
            ];
          } else if (q.qs_type === "qna") {
            // 简答题不需要选项
            Editoptions.value = [];
          } else {
            // 填充选项并设置 is_right
             Editoptions.value = q.options.map(opt => ({
              content: opt.option_content,
              is_right: opt.is_right,
              option_id: opt.option_id
            }));
             console.log(Editoptions.value);
            if (q.qs_type === "only_sel") {
              // 找到第一个正确选项的索引
              // const correctIndex = q.options.findIndex(opt => opt.is_right);
              // correctOption.value = correctIndex !== -1 ? correctIndex : 0; // 如果没有找到正确选项，设置为 null
            }
          }
          EditOptionsLength=Editoptions.value.length;
          console.log("EditOptionsLength"+EditOptionsLength);
                
        } else {
          ElMessage.error(response.data.msg || "获取试题详情失败");
        }
      } catch (error) {
        console.error("Error fetching single question:", error);
        ElMessage.error("网络错误，无法获取试题详情");
      }
    };
    const EditsaveQuestion = async () => {
      try {
        // 确保保存时处理判断题的正确选项状态
        if (Editform.value.qs_type === 'yesorno') {
          Editoptions.value[0].is_right = isRight.value;
          Editoptions.value[1].is_right = !isRight.value;

          Editform.value.update_options = Editoptions.value.map(option => ({
            option_id: option.option_id,
            option_content: option.content,
            is_right: option.is_right
          }));
          console.log("Update Options:", Editform.value.update_options);

        } else {
          // 针对其他题型的新增、更新和删除逻辑
          const filteredOptions = Editoptions.value.filter(option => option.is_insert === true);
          Editform.value.options = filteredOptions.map(option => ({
            option_content: option.content,
            is_right: option.is_right,
          }));

          const upOptions = Editoptions.value.filter(option => option.is_insert !== true);
          Editform.value.update_options = upOptions.map(option => ({
            option_id: option.option_id,
            option_content: option.content,
            is_right: option.is_right
          }));
        }

        Editform.value.delete_options = deleteOptionList;
        const response = await updateQuestion(Editform.value);
        if (response.data.status === 1) {
          ElMessage.success('试题更新成功！');
          deleteOptionList.splice(0, deleteOptionList.length);
          await fetchQuestionsData();
          EditdialogVisible.value = false;
        }
      } catch (error) {
        console.error("保存题目失败:", error);
        ElMessage.error("保存题目失败，请检查输入并重试。");
      }
    };

// 新建功能保存
    const AddsaveQuestion = async () => {
      try {
        // 创建新问题
        if (Addform.value.qs_type === "qna") {
          // 为 qna 类型准备特定的数据
          const direction = directions.value.find(
            dir => dir.point_id === parseInt(Addform.value.direction, 10)
          );
          const qnaData = {
            tech_id: parseInt(tech_id.value, 10),
            qs_title: Addform.value.title,
            point_id: parseInt(Addform.value.direction, 10),
            point_content: direction ? direction.point_content : "",
            right_ans: Addform.value.answer,
            qs_type: Addform.value.qs_type
          };

          // 调用新的 API 保存简答题
          await saveShortAnswerQuestionApi(qnaData); // 确保已正确导入
          ElMessage.success("简答题创建成功！");
        } else {
          // 处理其他题型的创建逻辑
          const requestData = {
            tech_id: parseInt(tech_id.value, 10),
            qs_title: Addform.value.title,
            point_id: parseInt(Addform.value.direction, 10),
            difficulty:
              Addform.value.difficulty !== ""
                ? parseInt(Addform.value.difficulty, 10)
                : null,
            qs_type: Addform.value.qs_type
          };

          // 根据题型添加选项
          if (Addform.value.qs_type === "only_sel") {
            requestData.options = options.value.map((option, index) => ({
              option_content: option.content,
              is_right: index === correctOption.value
            }));
          } else if (Addform.value.qs_type === "many_sel") {
            requestData.options = options.value.map(option => ({
              option_content: option.content,
              is_right: option.is_right
            }));
          } else if (Addform.value.qs_type === "yesorno") {
            requestData.right_ans = isRight.value ? "true" : "false";
            requestData.options = [
              { option_content: "正确", is_right: isRight.value },
              { option_content: "错误", is_right: !isRight.value }
            ];
          }

          // 移除 undefined 或 null 字段
          Object.keys(requestData).forEach(key => {
            if (requestData[key] === undefined || requestData[key] === null) {
              delete requestData[key];
            }
          });

          // 调用创建 API（假设 saveQuestionApi 不需要 config）
          await saveQuestion(requestData);
          ElMessage.success("试题创建成功！");
        }

        // 获取更新后的问题列表并关闭弹窗
        await fetchQuestionsData();
        AdddialogVisible.value = false;
      } catch (error) {
        console.error("保存题目失败:", error);
        ElMessage.error("保存题目失败，请检查输入并重试。");
      }
    };

    const batchDeleteSelectedQuestions = async () => {
       if (selectedQuestions.value.length === 0) {
    ElMessage.error("请先选择要删除的题目。");
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedQuestions.value.length} 个题目吗？`,
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    const qs_ids = selectedQuestions.value.join(",");
    await batchDeleteQuestions(qs_ids);
    ElMessage.success("选中的题目已成功删除。");
    await fetchQuestionsData();
    selectedQuestions.value = [];
  } catch (error) {
    // 取消操作会自动捕获
  }
};

    const deleteQuestionHandler = async question => {
       try {
          await ElMessageBox.confirm(
            '确定删除该题目吗？',
            '警告',
            {
              confirmButtonText: '删除',
              cancelButtonText: '取消',
              type: 'warning',
            }
          );
          await deleteQuestion(question.qs_id);
          ElMessage.success('题目已成功删除。');
          await fetchQuestionsData();
        } catch (error) {
          // 取消操作会自动捕获
        }
      };

    const resetForm = () => {
      Addform.value = {
        title: "",
        qs_type: "",
        direction: "",
        answer: "",
        difficulty: "",
        qs_id: null // 确保 qs_id 被重置
      };
      options.value = [{ content: "", is_right: false }];
      isRight.value = true; // 判断题默认选择正确
      correctOption.value = null; // 重置单选题的正确选项
    };

    const handlePageChange = newPage => {
      currentPage.value = newPage;
    };

    const getQuestionType = type => {
      return type === "only_sel"
        ? "单选"
        : type === "many_sel"
        ? "多选"
        : type === "yesorno"
        ? "判断"
        : type === "qna"
        ? "简答"
        : "未知类型";
    };

    const getDifficultyLabel = difficulty => {
      const labelMap = {
        "0": "简单",
        "1": "中等",
        "2": "困难"
      };
      return labelMap[difficulty] || "未知";
    };

    const getDirectionLabel = directionId => {
      const direction = directions.value.find(
        dir => dir.point_id === directionId
      );
      return direction ? direction.point_content : "其他";
    };

    const searchQuestions = () => {
      currentPage.value = 1;
      fetchQuestionsData(); // 重新获取数据以应用搜索
    };

    const toggleFilterDirection = (directionId) => {
      selectedFilterDirection.value = directionId;
      selectedFilterPoint.value = "all"; // 切换方向时，默认不过滤具体的 point
      fetchQuestionsData();
    };
     // **选择具体的题目方向（point）**
    const toggleFilterPoint = (pointId) => {
      selectedFilterPoint.value = pointId;
      fetchQuestionsData();
    };

    const toggleFilterQuestionType = type => {
      selectedQuestionType.value = type;
      currentPage.value = 1;
      fetchQuestionsData();
    };

    const toggleFilterDifficulty = difficulty => {
      selectedDifficulty.value = difficulty;
      currentPage.value = 1;
      fetchQuestionsData();
    };

    onMounted(() => {
      fetchDirections();
      fetchQuestionsData();
    });

    return {
      updateOnlySelCorrectOption,
      deleteOptionList,
      options,
      Editoptions,
      currentTab,
      questions,
      Addform,
      Editform,
      AdddialogVisible,
      EditdialogVisible,
      currentPage,
      pageSize,
      searchQuery,
      selectedFilterDirection,
      selectedQuestionType,
      selectedDifficulty,
      newQuestionMenuVisible,
      directions,
      filteredQuestions,
      paginatedData,
      totalPages,
      changeTab,
      openNewQuestionMenu,
      showAddDialog,
      editQuestion,
      AddsaveQuestion,
      EditsaveQuestion,
      deleteQuestionHandler,
      resetForm,
      handlePageChange,
      getQuestionType,
      getDifficultyLabel,
      getDirectionLabel,
      searchQuestions,
      toggleFilterDirection,
      toggleFilterQuestionType,
      toggleFilterDifficulty,
      isRight,
      addOption,
      removeOption,
      addOption1,
      removeOption1,
      selectedQuestions,
      allSelected,
      toggleSelectAll,
      batchDeleteSelectedQuestions, // 新增
      handleOptionChange,
      EditOptionsLength,
      Insertoptions,
       confirmSelection,
      closeDialog,
       selectQuestionForPopup,
       toggleFilterPoint,

    };
  }
};
</script>

<style scoped>
.question-details {
    display: block; /* 使用块级显示 */
}

.question-details summary {
    display: flex; /* 使用 flexbox 使内容对齐 */
    align-items: center;
    cursor: pointer;
    list-style: none; /* 去掉默认列表样式 */
}

.question-options {
    max-height: 0; /* 初始时隐藏内容 */
    overflow: hidden; /* 隐藏溢出内容 */
    transition: max-height 0.3s ease; /* 添加过渡效果 */
}

.question-details[open] .question-options {
    max-height: 500px; /* 展开时自适应高度 */
}

/* 添加三角形指示符的样式 */
.question-details summary::before {
    content: '▶'; /* 默认图标 */
    margin-right: 8px; /* 间距 */
}

.question-details[open] summary::before {
    content: '▼'; /* 展开后的图标 */
}

.question-options {
  margin-top: 5px;
  padding: 10px 0px 0px 0px;
}

.top-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.tab-bar {
  display: flex;
  background-color: white;
  padding: 10px;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  transition: background 0.3s ease-in-out;
}

.tab.active {
  border-bottom: 2px solid #244382;
  color: #244382;
  font-weight: bold;
}

.search-container {
  display: flex;
  align-items: center;
  position: relative;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 20px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

.action-button {
  background-color: #125aa2;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  margin-left: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

.action-button:hover {
  background-color: #0e4b8a;
}

.new-question-menu {
  width: 66px;
  align-items: center;
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border: 1px solid #ddd;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.new-question-menu span {
  cursor: pointer;
  padding: 5px 0;
  color: gray;
}

.secondary-filters {
  display: flex;
  flex-direction: column; /* 每个类别独占一行 */
  margin-bottom: 20px;
  font-size: 14px;
}

.filter-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-label {
  font-weight: bold;
  color: #666;
}

.secondary-filters span {
  padding: 5px 12px;
  cursor: pointer;
  border-radius: 4px;
  color: #333;
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}

.active-filter {
  color: #ffffff;
  background-color: #eaf4ff !important;; /* 更加鲜明的选中状态背景颜色 */
}

.secondary-filters span:hover:not(.active-filter) {
  background-color: #f0f0f0;
}

.question-table {
  width: 100%;
  border-collapse: collapse;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
  table-layout: fixed; /* 固定表格布局以确保列宽 */
  font-size: 13px;
}

.question-table th,
.question-table td {
  border: 1px solid #ddd;
  padding: 12px 15px;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.question-table th {
  background-color: #f7f7f7;
  color: #333;
}

.table-row:nth-child(even) {
  background-color: #f9f9f9;
}

.table-row:hover {
  background-color: #eef6ff;
}

.action-cell {
  position: relative;
  width: 100px;
}

.action-buttons {
  position: absolute;
  top: 50%;
  right: -120px; /* 初始隐藏 */
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 1px;
  transition: right 0.3s ease-in-out;
  flex-direction: row;
}

.table-row:hover .action-buttons {
  right: 5px; /* 悬停时滑出 */
}

.edit-button,
.delete-button {
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
  font-size: 14px;
  white-space: nowrap;
}

.select-button{
  background-color: #5e6b98;
  border: #0e4b8a;
  border-radius: 5px;
  padding: 5px 15px;
  font-size: 13px;
  color: white;
}
.select-button:hover{
  background-color: #0e4b8a;
  color: white;
}
.edit-button {
  background-color: #4caf50;
  padding: 5px 5px;
  font-size: 13px;
  color: white;
}

.edit-button:hover {
  text-decoration: underline;
}

.delete-button {
  padding: 5px 5px;
  font-size: 13px;
  color: white;
  background-color: #f44336;
}

.delete-button:hover {
  text-decoration: underline;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

.modal {
  position: fixed;
  width: 60vw;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px 50px;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
  z-index: 1001;
}

.modal-content {
  display: flex;
  flex-direction: column;
}
.modal-content label {
  margin: 10px 0px;
}

.option-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  margin: 14px 0px;
}

.option-group input {
  margin-right: 10px;
  height: 25px;
}

.modal-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-button {
  background-color: #ddd;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

.cancel-button:hover {
  background-color: #ccc;
}

.confirm-button {
  background-color: #125aa2;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

.confirm-button:hover {
  background-color: #0e4b8a;
}
.option-buttons {
  display: flex;
  align-items: center;
}

.option-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  padding: 0;
  margin-left: 5px;
}

.option-button img {
  width: 25px;
  height: 25px;
}

.option-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
.input-field.option-input {
  width: 500px; /* 固定宽度，根据需要调整 */
  margin-left: 5px;
}
.question-table th,
.question-table td {
  vertical-align: middle;
}

.no-results {
  text-align: center;
  padding: 20px;
}
.select-button {
  background-color: #f0f0f0;
  color:black;
  border: none;
  padding: 8px 16px;
  cursor: pointer;
}

.select-button.selected {
  background-color: #4caf50; /* 选中状态的按钮颜色 */
  color: white;
}

</style>
